package org.black.phoneUtility;

import java.util.HashSet;
import java.util.Set;

import org.black.phoneUtility.app.activity.PhoneUtilitySettingsActivity;
import org.black.phoneUtility.app.fragment.BackupAndRestoreFragment;
import org.black.phoneUtility.app.fragment.LoadingFragment;
import org.black.phoneUtility.app.service.StartNeededService;
import org.black.phoneUtility.sms.reply.app.fragment.SmsReplyFragment;
import org.black.phoneUtility.sms.schedule.app.fragment.SmsScheduleFragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
	public static final String ARGUMENTS_DRAWER_SELECT_ITEM = "arguments_drawer_select_item";

	public static final int DRAWER_SELECT_INVALID_ITEM = -1;
	public static final int DRAWER_SELECT_SMS_REPLY = 0;
	public static final int DRAWER_SELECT_BACKUP_RESTORE = 1;

	private static final String LOG_TAG = MainActivity.class.getName();
	private DrawerLayout drawerLayout = null;
	private ListView drawerListView = null;
	private ActionBarDrawerToggle actionBarDrawerToggle = null;

	private CharSequence drawerTitle = null;
	private CharSequence activityTitle = null;
	private String[] phoneUtilityFunctions = null;
	private Set<Class<?>> drawerClasses = null;
	private int drawerPosition = 0;

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		drawerPosition = savedInstanceState
				.getInt(ARGUMENTS_DRAWER_SELECT_ITEM);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		this.activityTitle = this.drawerTitle = this.getTitle();

		phoneUtilityFunctions = getResources().getStringArray(
				R.array.phone_utility_functions);
		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		drawerListView = (ListView) findViewById(R.id.left_drawer);

		drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		drawerListView.setAdapter(new ArrayAdapter<String>(this,
				R.layout.drawer_list_item, phoneUtilityFunctions));

		drawerListView.setOnItemClickListener(new DrawerItemClickListener());

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		drawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(activityTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()

				FragmentManager fragmentManager = getFragmentManager();
				if (drawerPosition == 0) {
					Fragment fragment = fragmentManager
							.findFragmentByTag(SmsReplyFragment.TAG);
					if (fragment == null) {
						fragment = new SmsReplyFragment();

						Bundle args = new Bundle();
						fragment.setArguments(args);
						fragmentManager
								.beginTransaction()
								.replace(R.id.content_frame, fragment,
										SmsReplyFragment.TAG).commit();
						Log.d(LOG_TAG, "Choose SmsReplyFragment!");
					}
				} else if (drawerPosition == 1) {
					Fragment fragment = fragmentManager
							.findFragmentByTag(SmsScheduleFragment.TAG);
					if (fragment == null) {
						fragment = new SmsScheduleFragment();

						Bundle args = new Bundle();
						fragment.setArguments(args);

						fragmentManager
								.beginTransaction()
								.replace(R.id.content_frame, fragment,
										SmsScheduleFragment.TAG).commit();
						Log.d(LOG_TAG, "Choose SmsScheduleFragment!");
					}
				} else {
					Fragment fragment = new BackupAndRestoreFragment();

					Bundle args = new Bundle();
					fragment.setArguments(args);

					fragmentManager.beginTransaction()
							.replace(R.id.content_frame, fragment).commit();
					Log.d(LOG_TAG, "Choose BackupAndRestoreFragment!");
				}
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(drawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};
		drawerClasses = new HashSet<Class<?>>();
		drawerClasses.add(SmsReplyFragment.class);
		drawerClasses.add(SmsScheduleFragment.class);
		drawerClasses.add(BackupAndRestoreFragment.class);

		drawerLayout.setDrawerListener(actionBarDrawerToggle);
		Bundle arguments = getIntent().getExtras();
		if (savedInstanceState == null && arguments == null) {
			selectItem(drawerPosition);
		} else if (savedInstanceState != null) {
			drawerPosition = savedInstanceState
					.getInt(ARGUMENTS_DRAWER_SELECT_ITEM);
			selectItem(drawerPosition);
		} else if (arguments != null
				&& arguments.getInt(ARGUMENTS_DRAWER_SELECT_ITEM,
						DRAWER_SELECT_INVALID_ITEM) != DRAWER_SELECT_INVALID_ITEM) {
			drawerPosition = arguments.getInt(ARGUMENTS_DRAWER_SELECT_ITEM);
			selectItem(drawerPosition);
		}

		Intent updateNotificationServiceIntent = new Intent(this,
				StartNeededService.class);
		Bundle startNeededServiceBundle = new Bundle();
		updateNotificationServiceIntent.putExtras(startNeededServiceBundle);
		startService(updateNotificationServiceIntent);
		Log.d(LOG_TAG, "Start StartNeededService!");
	}

	@Override
	protected void onResume() {
		super.onResume();
		actionBarDrawerToggle.onDrawerClosed(null);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.activityTitle = null;
		this.drawerTitle = null;
		this.drawerListView = null;
		this.drawerLayout = null;
		this.actionBarDrawerToggle = null;
		this.phoneUtilityFunctions = null;
		this.drawerClasses.clear();
		this.drawerClasses = null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		boolean drawerOpen = drawerLayout.isDrawerOpen(drawerListView);
		// TODO: hide menu on activity's
		menu.setGroupVisible(R.id.menu_group_sms_reply, !drawerOpen);
		menu.setGroupVisible(R.id.menu_group_sms_schedule, !drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (this.actionBarDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action buttons
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent intent = new Intent(this, PhoneUtilitySettingsActivity.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, requestCode, data);
		switch (requestCode) {

		}

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();

	}

	private void selectItem(int position) {
		drawerListView.setItemChecked(position, true);
		setTitle(phoneUtilityFunctions[position]);
		drawerLayout.closeDrawer(drawerListView);

		this.drawerPosition = position;

		FragmentManager fragmentManager = getFragmentManager();

		Fragment fragment = new LoadingFragment();
		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, fragment, LoadingFragment.TAG)
				.commit();
		this.actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
	}

	@Override
	public void setTitle(CharSequence title) {
		activityTitle = title;
		getActionBar().setTitle(activityTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		actionBarDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		actionBarDrawerToggle.onConfigurationChanged(newConfig);
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			selectItem(position);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(ARGUMENTS_DRAWER_SELECT_ITEM,
				this.drawerListView.getCheckedItemPosition());
		super.onSaveInstanceState(outState);
	}
}
